<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-01 15:57:23
 * @LastEditTime: 2022-11-30 09:55:09
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 新增/编辑部门
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :visible="visible"
    :destroyOnClose="true"
    :width="450"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-form-item label="部门名称" v-bind="validateInfos.name">
        <a-input placeholder="请输入部门名称" v-model:value="modelRef.name" />
      </a-form-item>
      <a-form-item label="上级部门" v-bind="validateInfos.parent_id">
        <TreeSelect
          v-model:value="modelRef.parent_id"
          :tree-data="departmentTree"
          allow-clear
          :treeDefaultExpandAll="tree"
          placeholder="请选择上级部门"
        ></TreeSelect>
      </a-form-item>
      <a-form-item label="部门负责人" v-bind="validateInfos.lead_uid">
        <a-tag
          v-if="selectedMember && selectedMember.realname"
          :closable="true"
          @close="handleTagClose"
          color="processing"
        >
          {{ selectedMember.realname }}
        </a-tag>
        <a-button type="primary" shape="circle" @click="chooseDeptLeader">
          <template #icon><EditOutlined /></template>
        </a-button>
      </a-form-item>
      <a-form-item v-bind="validateInfos.lead_uid">
        <template #label>
          <span>部门审批负责人</span>
          <text-tip
            tips="选择发放出入证后表单设计中默认添加姓名、手机号码、具体房号、车辆和人脸字段不可删除,并且在审批结束后会向审批人员添加的手机号账号中发送出入证"
          />
        </template>
        <template v-if="selectedApprover.length > 0">
          <a-tag
            color="processing"
            v-for="(item, index) of selectedApprover"
            :key="index"
            :closable="true"
            @close.prevent="handleApproverRemove(index)"
          >
            {{ item.realname }}
          </a-tag>
        </template>
        <a-button type="primary" shape="circle" @click="chooseDeptApprover">
          <template #icon><EditOutlined /></template>
        </a-button>
      </a-form-item>
      <a-form-item v-bind="validateInfos.type">
        <template #label>
          <span>部门层级</span>
          <text-tip
            :tips="['管理处/项目部绑定的项目决定了对应上级部门的权限，而项目部下的专业部门成员默认只会拥有项目部的项目权限','公司所属部门的人员如果拥有“电子合同配置”权限时，则可以管理该部门以及以下部门所绑定的公司的“电子合同配置”。公司下的专业部门成员默认只会拥有项目部的项目权限']"
          />
        </template>
        <a-select
          v-model:value="modelRef.type"
          :options="typeList"
          placeholder="请选择部门层级"
        />
      </a-form-item>
      <a-form-item
        label="绑定项目"
        v-bind="validateInfos.villageId"
        v-if="modelRef.type == 3"
      >
        <a-select
          v-model:value="modelRef.villageId"
          :options="villageList"
          placeholder="请绑定项目"
        />
      </a-form-item>

      <a-form-item  label="绑定公司" v-bind="validateInfos.org_branch_ids" v-if="needSelectCompany">
        <div style="position: relative">
          <a-button
            style="position: absolute; top: -34px; right: 0"
            @click="addCompany"
            type="link"
          >快速添加</a-button
          >
          <a-select
            v-model:value="modelRef.org_branch_ids"
            :options="companyList"
            placeholder="请选择公司"
            mode="multiple"
            allowClear
          />
        </div>
      </a-form-item>
<!--      <a-checkbox-->
<!--        v-if="needSelectCompany"-->
<!--        v-model:checked="modelRef.check_sub_company"-->
<!--      >-->
<!--        只查看该部门绑定公司及以下公司的合同、账单、流水。-->
<!--      </a-checkbox>-->
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button
        type="primary"
        :loading="submitLoading"
        @click.prevent="onSubmit"
        >保存</a-button
      >
    </div>

    <!-- 选择部门负责人 -->
    <ChooseOrgMember
      :visible="chooseMemberVisible"
      :getDetail="true"
      :deptDisabled="true"
      :uMax="1"
      @request="$utils.commonRequest"
      @close="closeChooseMemberModal"
      @success="handleMemberSelect"
    />

    <!-- 选择部门审批负责人 -->
    <ChooseOrgMember
      :visible="chooseApproverVisible"
      :getDetail="true"
      :deptDisabled="true"
      :uMax="-1"
      :checkedList="checkedApproverList"
      @request="$utils.commonRequest"
      @close="closeChooseApproverModal"
      @success="handleApproverSelect"
    />

    <!-- 快速添加分公司 -->
    <AddCompany
      :visible="addVisible"
      @handleCancel="addVisible = false"
      @handleSuccess="handleAddSuccess"
    />
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Form, message, TreeSelect } from "ant-design-vue";
import { ChooseOrgMember, TextTip } from "bl-common-vue3";
import { EditOutlined } from "@ant-design/icons-vue";
import store from "../../../../store";
const useForm = Form.useForm;
import request from "@/common/utils/request";
import _ from "lodash";
import AddCompany from "@/views/setting/CompanyInfo/modules/AddCompany.vue";

export default defineComponent({
  name: "EditDepartment",
  components: {AddCompany, TreeSelect, EditOutlined, ChooseOrgMember, TextTip },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 当前编辑的部门id
    id: {
      type: [String, Number],
      default: 0,
    },
    // 添加部门的父级部门id
    parentId: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    /**
     * @description: 标题显示
     */
    const title = computed(() => {
      return props.id ? "编辑部门" : "新增部门";
    });

    const departmentTree = computed(() => {
      // const list = store.getters.departmentList
      // console.log("------departmentTree", list);
      return store.getters.departmentList;
    });

    const needSelectCompany = computed(() => {
      return modelRef.type == 1 || modelRef.type == 2;
    });

    const state = reactive({
      villageList: [],
      // type 部门层级;0=总公司;1=区域分公司;2=分公司;3=管理处/项目部;4=专业部门;5=供应商
      typeList: [
        // { label: "总公司", value: 0 },
        { label: "区域分公司", value: 1 },
        { label: "分公司", value: 2 },
        { label: "管理处/项目部", value: 3 },
        { label: "专业部门", value: 4 },
        { label: "供应商", value: 5 },
      ],
      submitLoading: false,
      companyList: [],
      detailCompanyIds: '',
      addVisible: false,
    });

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      context.emit("closeEdit");
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      name: "",
      parent_id: undefined,
      villageId: undefined,
      type: undefined,
      org_branch_ids: undefined,
      check_sub_company: true,
    });

    watch(
      () => modelRef.type,
      (val) => {
        if (val == 3) {
          modelRef.villageId = detail.villageId || undefined;
          rulesRef.villageId = required;
        } else {
          delete rulesRef.villageId;
        }
        if (val == 1 || val == 2) {
          rulesRef.org_branch_ids = required;
        } else {
          delete rulesRef.org_branch_ids;
        }
      }
    );

    /**
     * @description: 验证规则
     */
    const required = [{ required: true, message: "必填项" }];
    const rulesRef = reactive({
      name: required,
      parent_id: required,
      type: required,
    });

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate()
        .then(() => {
          state.submitLoading = true;
          let params = { ...toRaw(modelRef), needMsg: true };
          if (selectedMember.value) {
            params.lead_uid = selectedMember.value.uid;
          }
          if (params.type == 3) {
            const selectVillage = state.villageList.find(
              (item) => item.value == params.villageId
            );
            params.build_bind = [
              {
                id: params.villageId,
                build: selectVillage.buildList.map((item) => item.id),
              },
            ];
          }
          if (needSelectCompany.value) {
            params.check_sub_company = params.check_sub_company ? 1 : 0;
          } else {
            delete params.check_sub_company;
            delete params.org_branch_ids;
          }
          if (selectedApprover.value.length > 0) {
            params.approval_lead_uid = selectedApprover.value.map(
              (item) => item.uid
            );
          }
          delete params.villageId;
          // console.log(params);
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success", "department");
          };
          if (props.id) {
            params.id = props.id;
            request.put("/org", "/department/index", params)
              .then((res) => success(res))
              .finally(() => {
                state.submitLoading = false;
              });
          } else {
            request.post("/org", "/department/index", params)
              .then((res) => success(res))
              .finally(() => {
                state.submitLoading = false;
              });
          }
        })
        .catch((err) => {
          console.log("error", err);
        });
    };

    /**
     * @description: 获取编辑信息
     */
    let detail = {};
    const getEditInfo = () => {
      return new Promise((resolve) => {
        request.get("/org", "/department/info", { id: props.id }).then((res) => {
          detail = res.detail;
          detail.villageId =
            detail.build_bind && detail.build_bind.length
              ? detail.build_bind[0].id
              : undefined;
          setModelRef({
            villageId: detail.villageId,
            name: detail.name,
            parent_id: detail.parent_id,
            type: detail.type,
            check_sub_company: detail.check_sub_company == 1 ? true : false,
            org_branch_ids: detail?.org_branch_ids || undefined,
          });
          if (detail?.org_branch_ids?.length) {
            state.detailCompanyIds = detail.org_branch_ids.join(',');
          }
          if (detail.leader) {
            selectedMember.value = detail.leader;
          }
          if (detail.approval_lead) {
            selectedApprover.value = detail.approval_lead;
            checkedApproverList.value.user = detail.approval_lead;
          }
          resolve()
        });
      });

    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    const chooseMemberVisible = ref(false);
    const chooseDeptLeader = () => {
      chooseMemberVisible.value = true;
    };

    // 关闭选择成员弹窗
    const closeChooseMemberModal = () => {
      chooseMemberVisible.value = false;
    };

    // 成员选中
    const selectedMember = ref();
    const handleMemberSelect = (data) => {
      selectedMember.value = data.user[0];
      closeChooseMemberModal();
    };

    const handleTagClose = () => {
      selectedMember.value = null;
    };

    const getVillageList = () => {
      if (state.villageList.length) {
        return;
      }
      request.get("/org", "/build/villageAndBuildList").then((res) => {
        state.villageList = res.villageList.map((item) => ({
          label: item.name,
          value: item.id,
          buildList: item.buildList,
        }));
      });
    };

    const getCompanyList = () => {
      let params = {};
      if (state.detailCompanyIds) {
        params.id = state.detailCompanyIds;
      }
      request.get("/org", "/department/branchList", params).then((res) => {
        state.companyList = (res?.list || []).map((v) => {
          return {
            value: v.id,
            label: v.company,
          }
        })
      });
    };

    // 部门审批负责人
    const chooseApproverVisible = ref(false);
    const chooseDeptApprover = () => {
      chooseApproverVisible.value = true;
    };

    // 关闭选择审批人弹窗
    const closeChooseApproverModal = () => {
      chooseApproverVisible.value = false;
    };

    const selectedApprover = ref([]);
    const checkedApproverList = ref({
      user: [],
      department: [],
    });
    const handleApproverSelect = (data) => {
      selectedApprover.value = data.user;
      checkedApproverList.value.user = data.user;
      closeChooseApproverModal();
    };

    const handleApproverRemove = (index) => {
      selectedApprover.value.splice(index, 1);
      checkedApproverList.value.user = selectedApprover.value;
    };

    const handleAddSuccess = () => {
      state.addVisible = false;
      getCompanyList()
    };

    const addCompany = () => {
      state.addVisible = true;
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      if (props.id) {
        getEditInfo().then(() => {
          getCompanyList();
        });
      } else {
        getCompanyList();
      }
      if (props.parentId) {
        modelRef.parent_id = props.parentId;
      }
      getVillageList();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          selectedMember.value = null;
          selectedApprover.value = [];
          checkedApproverList.value = {};
          state.companyList = [];
          state.detailCompanyIds = '';
        }
      }
    );

    return {
      departmentTree,
      needSelectCompany,
      ...toRefs(state),
      title,
      closeModal,
      validateInfos,
      resetFields,
      modelRef,
      onSubmit,
      chooseDeptLeader,
      chooseMemberVisible,
      closeChooseMemberModal,
      handleMemberSelect,
      selectedMember,
      handleTagClose,
      chooseApproverVisible,
      chooseDeptApprover,
      closeChooseApproverModal,
      handleApproverSelect,
      selectedApprover,
      handleApproverRemove,
      checkedApproverList,
      addCompany,
      handleAddSuccess,
    };
  },
});
</script>
